
#include "main.h"
#include "display.h"
#include "keybutton.h"
#include "eeprom.h"

#include <string.h>	/* for strlen */
#include <stdlib.h>	/* for atoi */


static void dispValue(u8 vdd, u8 sel)
{
	sprintf(gszLine, " VDD%d : %3d [mV]", vdd+1, (int)gVout[vdd].dwOffset);
	LcdLineString(6 + 2*vdd, LCD_ALIGN_CENTER, gszLine, sel ? COLOR_WHITE : COLOR_YELLOW, COLOR_BLACK);
}

void modeCalibration(u8 key, u32 first)
{
	static u8 _vdd = VOUT_1;	// 0(VDD1), 1(VDD2), 2(VDD3)
	int tmp;

	if (first) {
		LcdDrawRect(0, 0, LCD_SCREEN_WIDTH, LCD_SCREEN_HEIGHT, COLOR_BLACK);
		LcdLineString( 0, LCD_ALIGN_CENTER, STR_TITLE, COLOR_BLACK, COLOR_WHITE);
		LcdLineString(19, LCD_ALIGN_CENTER, "Mode : Calibration", COLOR_BLACK, COLOR_WHITE);

		LcdLineString( 2, LCD_ALIGN_LEFT, "  [F3] Exit", COLOR_YELLOW, COLOR_BLACK);

		LcdLineString( 4, LCD_ALIGN_CENTER, "<- Offset ->", COLOR_YELLOW, COLOR_BLACK);

		_vdd = VOUT_1;

		for (u32 y=VOUT_1; y<VOUT_MAX; y++) {
			dispValue(y, (_vdd == y) ? 1 : 0);
		}
	}

	switch (key) {
	case KEYBUTTON_UP:
		tmp = _vdd;
		if (VOUT_1 == _vdd) {
			_vdd = VOUT_MAX - 1;
		} else {
			_vdd--;
		}
		dispValue(tmp, 0);
		dispValue(_vdd, 1);
		break;
	case KEYBUTTON_DOWN:
		tmp = _vdd++;
		if (VOUT_MAX <= _vdd) {
			_vdd = VOUT_1;
		}
		dispValue(tmp, 0);
		dispValue(_vdd, 1);
		break;
	case KEYBUTTON_LEFT:
		gVout[_vdd].dwOffset--;
		dispValue(_vdd, 1);
		break;
	case KEYBUTTON_RIGHT:
		gVout[_vdd].dwOffset++;
		dispValue(_vdd, 1);
		break;
	case KEYBUTTON_F3:
		EE_WriteVariable32(EEPROM_VOUT1_OFFSET_L, gVout[VOUT_1].dwOffset);
		EE_WriteVariable32(EEPROM_VOUT2_OFFSET_L, gVout[VOUT_2].dwOffset);
		EE_WriteVariable32(EEPROM_VOUT3_OFFSET_L, gVout[VOUT_3].dwOffset);
		gvCurMode = MODE_READY;
		break;

	case KEYBUTTON_OK:
		/*{
			u32 addr = 0;
			switch (_vdd) {
			case VOUT_1:
				addr = EEPROM_VOUT1_SET_L;
				break;
			case VOUT_2:
				addr = EEPROM_VOUT2_SET_L;
				break;
			case VOUT_3:
				addr = EEPROM_VOUT3_SET_L;
				break;
			}

			tmp = atoi(gszEdit);
			if (2000 < tmp) {
				tmp = 2000;
				sprintf(gszEdit, "%d", 2000);
			}
			switch (_line - LINE_MIN) {
			case 0:	// SetMin
				gVout[_vdd].dwSet &= 0xFFFF0000;
				gVout[_vdd].dwSet |= (tmp << 0);
				EE_WriteVariable32(addr, gVout[_vdd].dwSet);
				break;
			case 1:	// GetMin
				gVout[_vdd].dwGet &= 0xFFFF0000;
				gVout[_vdd].dwGet |= (tmp << 0);
				EE_WriteVariable32(addr+2, gVout[_vdd].dwGet);
				break;
			case 3:	// SetMax
				gVout[_vdd].dwSet &= 0x0000FFFF;
				gVout[_vdd].dwSet |= (tmp << 16);
				EE_WriteVariable32(addr, gVout[_vdd].dwSet);
				break;
			case 4:	// GetMax
				gVout[_vdd].dwGet &= 0x0000FFFF;
				gVout[_vdd].dwGet |= (tmp << 16);
				EE_WriteVariable32(addr+2, gVout[_vdd].dwGet);
				break;
			}

			dispValue(_vdd, _line, 1);
			_first = 1;
		}*/
		break;
	}
}

